<template>


  <el-dialog
    top="20px"
    :title="defaultValue.title"
    :lock-scroll="tableConfig.lockScroll"
    :append-to-body="tableConfig.appendToBody"
    :visible="tableConfig.show"
    @close="tableConfig.show = false"
    :show-close="tableConfig.close"
    :destroy-on-close="tableConfig.destroyOnClose"
    width="1100px">

    <el-form size="small" ref="formOpsCommonUseRef" :rules="checkRule" :model="submitData" label-width="180px">


        <el-form-item label="类型" prop="folder">
          <el-input value="文件夹" v-if="submitData.folder === 1" disabled />
          <el-input value="文件" v-else-if="submitData.folder === 0" disabled />
        </el-form-item>
        <el-form-item label="上级名称" prop="parentId">
            <el-input v-model="parent.name" disabled />
        </el-form-item>


        <el-form-item label="名称" prop="name">
            <el-input placeholder="不填写则默认将上传文件的名称补充在这里" v-model="submitData.name" />
        </el-form-item>
        <el-form-item label="是否保密文件" prop="secrecy">
          <el-radio v-model="submitData.secrecy" :label=1>保密文件</el-radio>
          <el-radio v-model="submitData.secrecy" :label=0>非保密文件</el-radio>
        </el-form-item>
        <el-form-item label="是否重要文件" prop="core">
          <el-radio v-model="submitData.core" :label=1>重要文件</el-radio>
          <el-radio v-model="submitData.core" :label=0>非重要文件</el-radio>
        </el-form-item>

        <el-form-item label="文件" prop="fileId" v-if="submitData.folder === 0">
            <!--<el-input v-model="submitData.fileId" />-->
            <el-upload class="upload-demo" drag
                       action="#"
                       :auto-upload="false"
                       :on-change="handleFileChange"
                       :http-request="customUpload"
                       :show-file-list="false">
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <div class="el-upload__tip" slot="tip">注意：保存后不能再次修改</div>
            </el-upload>
            <div>

            </div>
            <!-- 显示上传状态 -->
            <div v-if="uploadFile.uploadStatus.message" :class="['upload-status', uploadFile.uploadStatus.type]">
              {{ uploadFile.uploadStatus.message }}
              <p v-if="uploadFile.fileInfo != null">文件名称：{{uploadFile.fileInfo.originalFilename}}</p>
              <p v-if="uploadFile.fileInfo != null">文件大小： {{formattedFileSize}} </p>
            </div>
        </el-form-item>

    </el-form>


    <span slot="footer" class="dialog-footer">
      <el-button plain type="warning" @click="toSaveUpd"
                 v-if="defaultValue.saveUpdSelect !== 'select'">{{ defaultValue.title }}
                 </el-button>
      <el-button plain type="primary" @click="tableConfig.show = false">关闭</el-button>
    </span>

  </el-dialog>


</template>

<script>

import http from '@/utils/http'
import {clearInvalid} from "@/utils/utils"

export default {
  name: "OpsCommonUseSaveUpd",
  data() {
    return {
      // 上传文件用到的参数
      uploadFile:{
        // 存储选择的文件
        selectedFile: null,
        // 上传后返回的文件信息
        fileInfo: {},
        // 上传状态信息
        uploadStatus: {
          message: '',
          // 'success' 或 'error'
          type: ''
        },
      },
      // 表格的默认值
      tableConfig: {
        // 关闭时销毁 Dialog 中的元素
        destroyOnClose: true,
        // 弹出框是否打开
        show: false,
        // 是否显示关闭按钮
        close: true,
        // 下面2个属性解决打开弹出框后没有在最上面显示的问题，导致看到的内容是一半的，需要先将滚动条移到最上面
        lockScroll: false,
        appendToBody: true,
      },
      // 默认值，进入页面后的值
      defaultValue: {
        // 弹出框标题
        title: '查看',
        // 保存还是修改or查看,取值有 select | save | upd
        saveUpdSelect: 'select'
      },
      // 上级现场文件
      parent:{},
      // 提交的数据
      submitData:{
        id: null,
        type: null,
        bindId: null,
        parentId: null,
        parentIds: null,
        folder: null,
        name: null,
        secrecy: null,
        core: null,
        fileId: null,
        createTime: null,
        updateTime: null,
        updateId: null,
        createId: null,
        delType: null,
      },
      // 校验规则
      checkRule: {
        id: [{required: true, message: '请输入主键', trigger: 'blur'}],
        parentId: [{required: true, message: '请输入上级id,顶层为-1', trigger: 'blur'}],
        parentIds: [{required: true, message: '请输入全部上级，不含-1', trigger: 'blur'}],
        folder: [{required: true, message: '请输入是否文件夹', trigger: 'blur'}],
        name: [{required: true, message: '请输入名称', trigger: 'blur'}],
        secrecy: [{required: true, message: '请输入是否保密文件，只有文件有', trigger: 'blur'}],
        core: [{required: true, message: '请输入是否重要文件', trigger: 'blur'}],
        fileId: [{required: true, message: '请输入文件id', trigger: 'blur'}],
        createTime: [{required: true, message: '请输入数据创建时间', trigger: 'blur'}],
        updateTime: [{required: true, message: '请输入数据更新时间', trigger: 'blur'}],
        updateId: [{required: true, message: '请输入数据更新人ID', trigger: 'blur'}],
        createId: [{required: true, message: '请输入数据创建人ID', trigger: 'blur'}],
        delType: [{required: true, message: '请输入数据是否有效', trigger: 'blur'}],
      },
    }
  },
  /**
   * 计算属性
   */
  computed: {
    formattedFileSize() {
      if (!this.uploadFile.fileInfo.size) return "0 B";
      return this.formatBytes(this.uploadFile.fileInfo.size);
    },
  },
  methods: {
    /*
    ================== 上传文件用到的参数 start
     */
    /**
     * 转换为人能识别的文件大小
     * @param bytes 字节数
     * @param decimals 保留小数
     * @returns {string}
     */
    formatBytes(bytes, decimals = 2) {
      if (bytes === 0) return "0 B";
      const k = 1024;
      const sizes = ["B", "KB", "MB", "GB", "TB"];
      const i = Math.floor(Math.log(bytes) / Math.log(k));
      return parseFloat((bytes / Math.pow(k, i)).toFixed(decimals)) + " " + sizes[i];
    },
    /**
     * 文件选择变化时触发
     * @param file 选择的文件
     */
    handleFileChange(file) {
      this.uploadFile.selectedFile = file.raw
      // 重置状态
      this.uploadFile.uploadStatus = { message: '', type: '' }
      // 选择文件后立即上传
      this.customUpload({ file: file.raw })
    },
    /**
     * 自定义上传方法
     * @param options
     * @returns {Promise<void>}
     */
    async customUpload(options) {
      const { file } = options
      const formData = new FormData()
      formData.append('file', file)
      const now = new Date();
      const year = now.getFullYear();
      // 月份从0开始，需要+1
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');
      formData.append('typePath', 'commonUse/' + year + "/" + month)
      formData.append('objectType', '5')

      const response = await http.postFileForm("/fileStorage/uploadFile", formData).then(response => {
        let res = response.data;
        this.submitData.fileId = res.data.id
        this.uploadFile.fileInfo = res.data
        if (this.submitData.name == null || this.submitData.name === '') {
          this.submitData.name = res.data.originalFilename
        }
        this.$message.success("上传文件成功");

        this.uploadFile.uploadStatus = {
          message: `上传成功！`,
          type: 'success'
        }

      }).catch(error => {
        this.$message.error(error.message);
        // 模拟失败回调
        this.uploadFile.uploadStatus = {
          message: `上传失败: ${error.message}`,
          type: 'error'
        }

      }).finally(() => {
        // 重置上传标志位
        console.log("上传触发")
      })
    },

     /*
     ================== 上传文件用到的参数 end
      */

    /**
     * 初始化操作
     * @param operateType 操作类型,保存还是修改or查看,取值有 select \ save \ upd
     * @param obj 如果是修改和查看，则是详细数据,需要赋值
     * @param parent 上级
     */
    init(operateType, obj, parent){
      this.defaultValue.saveUpdSelect = operateType
      this.parent = parent
      this.clearOldData()
      if (operateType === 'save'){
        this.submitData.parentId = obj.parentId
        this.submitData.folder = obj.folder
        this.submitData.secrecy = obj.secrecy
        this.submitData.core = obj.core
        this.submitData.bindId = obj.bindId
        this.submitData.type = obj.type
        this.defaultValue.title = '新增'

      } else if (operateType === 'upd'){
        this.defaultValue.title = '修改'
        // 要json处理下，否则会影响之前的值
        this.submitData = JSON.parse(JSON.stringify(obj))

      } else {
        // 可能查看
      }

      this.tableConfig.show = true
    },
    /**
     * 清理掉旧数据
     */
    clearOldData(){
      this.submitData = {
        id: null,
        type: null,
        bindId: null,
        parentId: null,
        parentIds: null,
        folder: null,
        name: null,
        secrecy: null,
        core: null,
        fileId: null,
        createTime: null,
        updateTime: null,
        updateId: null,
        createId: null,
        delType: null,
      }
      this.uploadFile = {
        // 存储选择的文件
        selectedFile: null,
        // 上传后返回的文件信息
        fileInfo: {},
        // 上传状态信息
        uploadStatus: {
          message: '',
          // 'success' 或 'error'
          type: ''
        },
      }
    },
    /**
     * 是保存还是修改
     */
    toSaveUpd(){
      if (this.defaultValue.saveUpdSelect === 'save'){
        this.saveCommonUse()

      } else if (this.defaultValue.saveUpdSelect === 'upd'){
        this.updCommonUse()

      } else {

      }
    },
    /**
     * 保存
     */
    saveCommonUse(){
      this.submitData.id = null
      http.post("/commonUse/saveCommonUse", this.submitData).then(response => {
        let res = response.data;
        this.$message.success ("保存成功");
        this.$emit('getCommonUseTree', null)
        // 关闭弹出框,继续添加
        this.tableConfig.show = false

      }).catch(error => {
        this.$message.error (error.message);
      })
    },
    /**
     * 更新
     */
    updCommonUse(){
      clearInvalid(this.submitData)
      http.post("/commonUse/updCommonUse", this.submitData).then(response => {
        let res = response.data;
        this.$message.success ("更新成功");
        this.$emit('getCommonUseTree', null)
        // 关闭弹出框
        this.tableConfig.show = false

      }).catch(error => {
        this.$message.error (error.message);
      })
    },
  }
}
</script>

<style scoped>

.upload-status {
  margin-top: 15px;
  padding: 10px;
  border-radius: 4px;
}

.upload-status.success {
  color: #67c23a;
  background-color: #f0f9eb;
}

.upload-status.error {
  color: #f56c6c;
  background-color: #fef0f0;
}

</style>


